import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form, Input, Select, Button, Radio, DatePicker, Checkbox, Row, Col, Cascader, message, Modal
} from 'antd';
import * as ajax from "../../../services/api";
import moment from 'moment';
import Drawer from 'react-motion-drawer';

import './less/report.less';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const confirm = Modal.confirm;
const dateFormat = 'YYYY-MM-DD';

@connect(state => ({
  profile: state.profile,
}))

@Form.create()

export default class AddDistrictDetails extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open2: this.props.visible,
      loading: false,
      securityRange: [],//安保范围
      crossManageId: this.props.crossManageId,//传过来的方案id
      areas: [],//地区
      messageList: {
        province: '',
        city: '',
        area: '',
        address: '',//详细地址
        recordPoliceName: '',//备案公安机关名称
        recordDate: '',//备案日期
        responsPer: '',//负责人
        responsPerPhone: '',//负责人手机号
        idCardNo: '',//负责人身份证号
        post: '',//负责人职务
        startDate: '',//跨区经营开始日期
        telePhone: '',//联系电话
        securityRange: [],//安保范围
        securityRangeContentArrays: [],//安保范围数组
      },
      fan: false,//返回之前是否保存
    }
  };

  componentWillReceiveProps(props) {
    this.setState({ open2: props.visible, crossManageId: props.crossManageId }, () => {
      console.log(this.state.open, this.state.crossManageId)
    });
  }

  componentDidMount() {
    this.props.onRef(this);
    this.securityRangeList();
    // this.messageList();
    this.getDistrict();//省市区选择
    console.log('thisthisTwo', this);
  }

  //省市区
  getDistrict = () => {
    ajax.getDistrictData().then((data) => {
      console.log('省市区data:', data);
      let areas = data.data.map((val) => {
        return {
          value: val.regionId,
          label: val.regionName,
          children: val.childs.map((valChild) => {
            return {
              value: valChild.regionId,
              label: valChild.regionName,
              children: valChild.childs.map((valChildChild) => {
                return {
                  value: valChildChild.regionId,
                  label: valChildChild.regionName,
                }
              })
            }
          })
        };
      }
      );
      //console.log('areas:'+JSON.stringify(areas));
      this.setState({
        areas: areas,
      });
    })
  };
//重置表单
resetFrom = () => {
  const { setFieldsValue } = this.props.form;
  setFieldsValue({
      EconomicType:'',
      address:'',//详细地址
      recordPoliceName:'',//备案公安机关名称
      recordDate:null,//备案日期
      responsPer:'',//负责人
      responsPerPhone:'',//负责人手机号
      idCardNo:'',//负责人身份证号
      post:'',//负责人职务
      startDate:null,//跨区经营开始日期
      telePhone:'',//联系电话
      securityRange:[],//安保范围
      securityRangeContentArrays:[],//安保范围数组
  });
}

//安保范围
securityRangeList = () =>{
  ajax.getDictInformation({codeTypes:'securityRange'}).then((data) => {
    if (data.data) {
      this.setState({
        securityRange: data.data.securityRange,
      });
    }
  })
};

//提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('保存-修改跨区经营', values);
        values.province = values.EconomicType[0];
        if (values.EconomicType[1]) {
          values.city = values.EconomicType[1];
        } else {
          values.city = 0;
        }
        if (values.EconomicType[2]) {
          values.area = values.EconomicType[2];
        } else {
          values.area = 0;
        }
        values.recordDate = values['recordDate'].format('YYYY-MM-DD');
        values.startDate = values['startDate'].format('YYYY-MM-DD');
        delete values.EconomicType;
        values.securityRangeContentArrays = values.securityRange;
        if (this.state.crossManageId !== '00') {
          values.crossManageId = this.state.crossManageId;
        }
        let d1 = new Date(values.startDate.replace(/\-/g, "\/"));
        let d2 = new Date(values.recordDate.replace(/\-/g, "\/"));
        if (d1 < d2) {
          message.error('跨区经营开始日期不能早于备案日期');
        } else {
          this.setState({ loading: true });
          ajax.comStockSaveCrossManage({ ...values }).then((data) => {
            // console.log('提交成功');
            // message.success('跨区经营详情保存成功！');
            this.setState({
              fan: true,
              loading: false,
            }, () => {
              this.props.close();
            });
          }, (err) => {
            this.setState({ loading: false });
          });
        }
      }
    });
  };

  callback = (key) => {
    console.log(key);
  };

  onChangeCheck = (checkedValues) => {
    console.log('checked = ', checkedValues);
  };

  //安保范围选择
  renderList = () => {
    return this.state.securityRange.map((val, key) => {
      return <Col key={key} span={8} style={{ marginTop: '5px' }}><Checkbox value={val.codeValue + ""}>{val.label}</Checkbox></Col>
    });
  };

  fan = () => {
    let _that = this;
    if (_that.state.fan) {
      // _that.props.history.push(`/enterprise/reported/districtbasic`);
      _that.props.close();
    } else {
      confirm({
        title: '当前信息未保存，是否确认返回？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          // _that.props.history.push(`/enterprise/reported`);
          // _that.props.close();
          _that.setState({
            open2: false
          });
          // _that.resetFrom();
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  };

  //验证手机号码
  checkPhone = (rule, value, callback) => {
    if (value && !(/^1[0-9]{10}$/).test(value)) {
      callback('请输入正确的手机号码！');
    } else {
      callback();
    }
  };

  //验证固定号码
  checkLandlinePhone = (rule, value, callback) => {
    if (value && !(/^0\d{2,3}-?\d{7,8}$/).test(value)) {
      callback('请输入正确的联系电话！');
    } else {
      callback();
    }
  };

  //验证身份证号码
  checkIdCardNo = (rule, value, callback) => {
    if (value && !(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/).test(value)) {
      callback('请输入正确的身份证号码！');
    } else {
      callback();
    }
  };

  checkPersonName = (rule, value, callback) => {
    if (value && !(/^[\u4e00-\u9fa5_a-zA-Z]+$/).test(value)) {
      callback('请输入正确的负责人姓名！');
    } else {
      callback();
    }
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    // const { setFieldsValue } = this.props.form;
    const config = {
      rules: [{ type: 'object', required: true, message: '请选择日期!' }],
    };

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };


    return (
      <Drawer
        overlayColor="rgba(0, 0, 0,0)"
        right
        open={this.state.open2}
        noTouchClose
        width={600}
        zIndex={2}
        className="drawer-box"
        onChange={(open) => {
          this.props.onChange(open);
          this.setState({ open });
        }}
      >
        <h3 style={{"fontSize":'22px',"padding":"18px",'borderBottom':'1px solid #dedede'}}>新增记录</h3>
        <Form onSubmit={this.handleSubmit}>
          {this.state.crossManageId === '00' ? <FormItem
            {...formItemLayout}
            label="跨区经营地址"
          >
            {getFieldDecorator('EconomicType', {
              rules: [{ required: true, message: '请选择跨区经营地址' }],
            })(
              <Cascader options={this.state.areas} placeholder="请选择" />
            )}
          </FormItem> : <FormItem
            {...formItemLayout}
            label="跨区经营地址"
          >
              {getFieldDecorator('EconomicType', {
                initialValue: [this.state.messageList.province, this.state.messageList.city, this.state.messageList.area],
                rules: [{ required: true, message: '请选择跨区经营地址' }],
              })(
                <Cascader options={this.state.areas} placeholder="请选择" />
              )}
            </FormItem>}

          <FormItem
            {...formItemLayout}
            label=" "
            colon={false}
            className="detailedAddress"
          >
            {getFieldDecorator('address', {
              initialValue: this.state.messageList.address,
              rules: [{
                required: true,
                message: '请输入跨区经营具体地址',
              }],
            })(
              <TextArea row={2} placeholder="" maxLength="50" />
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label="备案公安机关名称"
          >
            {getFieldDecorator('recordPoliceName', {
              initialValue: this.state.messageList.recordPoliceName,
              rules: [{
                required: true, message: '请输入备案公安机关名称',
              }, {
                pattern: /^[\u4E00-\u9FA5\（\）]{1,20}$/,
                message: "请输入中文最大长度20"
              }],
            })(
              <Input placeholder="请输入" maxLength="20" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="负责人"
          >
            {getFieldDecorator('responsPer', {
              initialValue: this.state.messageList.responsPer,
              rules: [{
                required: true, message: '请输入负责人',
              }, {
                pattern: /^[\u4E00-\u9FA5]{1,10}$/,
                message: "请输入中文最大长度20"
              }],
            })(
              <Input placeholder="请输入" maxLength="10" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="负责人手机号"
          >
            {getFieldDecorator('responsPerPhone', {
              initialValue: this.state.messageList.responsPerPhone,
              rules: [{
                required: true, message: '请输入负责人手机号',
              }, {
                validator: this.checkPhone
              }],
            })(
              <Input placeholder="请输入" maxLength="11" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="负责人职务"
          >
            {getFieldDecorator('post', {
              initialValue: this.state.messageList.post,
              rules: [{
                pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/,
                message: "请输入负责人，中文或英文"
              }, { required: true, message: '请选择负责人职务' }],
            })(
              <Input placeholder="请输入" maxLength="20" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="负责人身份证号"
          >
            {getFieldDecorator('idCardNo', {
              initialValue: this.state.messageList.idCardNo,
              rules: [{
                required: true, message: '请输入负责人身份证号',
              }, {
                validator: this.checkIdCardNo
              }],
            })(
              <Input placeholder="请输入" maxLength="18" />
            )}
          </FormItem>

          {this.state.crossManageId === '00' ? <FormItem
            {...formItemLayout}
            label="跨区经营开始日期"
          >
            {getFieldDecorator('startDate', {
              rules: [{ type: 'object', required: true, message: '跨区经营开始日期不能为空' }],
            })(
              <DatePicker style={{ width: '100%' }} />
            )}
          </FormItem> : <FormItem
            {...formItemLayout}
            label="跨区经营开始日期"
          >
              {getFieldDecorator('startDate', {
                initialValue: moment(this.state.messageList.startDate, dateFormat),
                rules: [{ type: 'object', required: true, message: '跨区经营开始日期不能为空' }],
              })(
                <DatePicker style={{ width: '100%' }} />
              )}
            </FormItem>}

          {this.state.crossManageId === '00' ? <FormItem
            {...formItemLayout}
            label="备案日期"
          >
            {getFieldDecorator('recordDate', {
              rules: [{ type: 'object', required: true, message: '备案日期不能为空' }],
            })(
              <DatePicker style={{ width: '100%' }} />
            )}
          </FormItem> : <FormItem
            {...formItemLayout}
            label="备案日期"
          >
              {getFieldDecorator('recordDate', {
                initialValue: moment(this.state.messageList.recordDate, dateFormat),
                rules: [{ type: 'object', required: true, message: '备案日期不能为空' }],
              })(
                <DatePicker style={{ width: '100%' }} />
              )}
            </FormItem>}


          <FormItem
            {...formItemLayout}
            label="联系电话"
          >
            {getFieldDecorator('telePhone', {
              initialValue: this.state.messageList.telePhone,
              rules: [{
                required: true, message: '请输入联系电话',
              }, {
                validator: this.checkLandlinePhone
              }],
            })(
              <Input placeholder="请输入" maxLength="15" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="安保范围"
          >
            {getFieldDecorator('securityRange', {
              initialValue: this.state.messageList.securityRangeContentArrays,
              rules: [{
                required: true, message: '请选择安保范围',
              }],
            })(
              <Checkbox.Group onChange={this.onChangeCheck}>
                <Row>
                  {this.renderList()}
                </Row>
              </Checkbox.Group>
            )}
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button loading={submitting} onClick={this.fan}>返回
          </Button>
            <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit" loading={this.state.loading}>提交</Button>
          </FormItem>
        </Form>
        {/*</div>*/}
      </Drawer>
    );
  }
}
